package com.ficus.road.maintain.third.zh.xlj;

import com.alibaba.fastjson.JSONArray;
import com.ficus.road.maintain.core.model.xlj.Xlj;
import com.ficus.road.maintain.core.model.zh.xlj.XljBasicInfoZH;
import com.ficus.road.maintain.core.model.zh.xlj.XljWarning;
import com.ficus.road.maintain.dao.xlj.XljDao;
import com.ficus.road.maintain.dao.xlj.XljNatureDao;
import com.ficus.road.maintain.dao.xlj.XljWarningDao;
import com.ficus.road.maintain.third.dk.DKCameraInfo;
import com.ficus.road.maintain.third.zh.BaseZH;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import static com.ficus.road.maintain.util.LngLonUtil.out_of_china;

/**
 * @author xiawen yang
 * @date 2022/4/15 下午5:18
 */
@Component
@Slf4j
public class ZHXljBasicInfo extends BaseZH {

    @Autowired
    private XljDao xljDao;
    @Autowired
    private XljNatureDao xljNatureDao;
    @Autowired
    private DKCameraInfo dkCameraInfo;
    @Value("${present.flag}")
    private Boolean present;

    @PostConstruct
    void init() {
        arg0 = "sanwangXljBase";
        arg1 = "";
        errMsg = "调用中海接口获取下立交基础信息异常!";
        successMsg = "调用中海接口获取下立交基础信息成功!";
    }

    @Scheduled(cron = "0 0 0/1 * * ?", zone = "GMT+8:00")
//    @Scheduled(cron = "0/5 * * * * ?", zone = "GMT+8:00")
    public void refreshXljBasicInfo() {
        init();
        String xljStr = getZHData();
        if (StringUtils.isEmpty(xljStr)) {
            return;
        }
        Date date = new Date();
        List<XljBasicInfoZH> xljBasicInfoZHList = JSONArray.parseArray(xljStr, XljBasicInfoZH.class);
        List<Xlj> xljList = xljBasicInfoZHList.stream().map(item -> item.convert2Xlj(item, date)).collect(Collectors.toList());
        Set<String> zhonghaiIdSet = xljList.stream().map(Xlj::getId).collect(Collectors.toSet());
        List<Xlj> collect = xljDao.findAll().stream().filter(t -> !zhonghaiIdSet.contains(t.getId())).collect(Collectors.toList());
        collect.forEach(t -> xljDao.deleteById(t.getId()));

        xljList.forEach(xlj -> {

            //gps 不合法则丢弃
            if (StringUtils.isNotEmpty(xlj.getLatitude()) && StringUtils.isNumeric(xlj.getLongitude())
                    && out_of_china(Double.parseDouble(xlj.getLongitude()), Double.parseDouble(xlj.getLatitude()))) {
                return;
            }

            Xlj fetch = xljDao.fetch(xlj.getId());
            if (ObjectUtils.isEmpty(fetch)) {
                xljDao.insert(xlj);
                return;
            }
            xlj.setXljLatestInfo(fetch.getXljLatestInfo());
            xlj.setCameras(fetch.getCameras() == null ? Lists.newArrayList() : fetch.getCameras());
            if (StringUtils.isNotEmpty(fetch.getXljNature())) {
                xlj.setXljNature(fetch.getXljNature());
            }

            if (StringUtils.isEmpty(xlj.getXljNature())) {
                xlj.setXljNature("");
            }

            xljDao.saveOrUpdate(xlj);
        });
    }

    void refresh() {
        init();
        String xljStr = getZHData();
        if (StringUtils.isEmpty(xljStr)) {
            return;
        }
        Date date = new Date();
        List<XljBasicInfoZH> xljBasicInfoZHList = JSONArray.parseArray(xljStr, XljBasicInfoZH.class);
        List<Xlj> zhXljList = xljBasicInfoZHList.stream().map(item -> item.convert2Xlj(item, date)).collect(Collectors.toList());
        List<Xlj> dbXljList = xljDao.findAll();
        AtomicInteger success = new AtomicInteger(0);
        AtomicInteger fail = new AtomicInteger(0);
        Set<String> dbXljIdSet = dbXljList.stream().map(Xlj::getId).collect(Collectors.toSet());
        Set<String> zhXljIdSet = zhXljList.stream().map(Xlj::getId).collect(Collectors.toSet());
        dbXljIdSet.removeAll(zhXljIdSet);
        System.out.println(dbXljIdSet.size());
        dbXljIdSet.forEach(item -> {
            xljDao.deleteById(item);
        });
//        zhXljList.forEach(zhXlj -> {
//            Optional<Xlj> dbXljOptional = dbXljList.stream().filter(dbXlj -> Objects.equal(dbXlj.getUniIdHuwan(), zhXlj.getUniIdHuwan())).findAny();
//            if (dbXljOptional.isEmpty()) {
//                log.error("error, uniId: {}", zhXlj.getUniIdHuwan());
//                fail.getAndIncrement();
//            } else {
//                Xlj dbXlj = dbXljOptional.get();
//                Xlj newDbXlj = JsonUtils.deepCopy(dbXlj, Xlj.class);
//                newDbXlj.setId(zhXlj.getId());
//                xljDao.saveOrUpdate(newDbXlj);
//                success.getAndIncrement();
//            }
//        });
//        System.out.println("---------------------------------------");
//        // 删除脏数据
//        dbXljList.forEach(dbXlj -> {
//            xljDao.deleteById(dbXlj.getId());
//        });
//        log.info("success: {}, fail: {}", success.get(), fail.get());
    }

    @Override
    public boolean printLogInfo() {
        return false;
    }

    //    @Scheduled(cron = "0/5 * * * * ?", zone = "GMT+8:00")
    void refreshXljNature() {
        List<Xlj> all = xljNatureDao.findAll();
        all.forEach(xlj -> {
            Xlj xljDb = xljDao.findOne(new Query(Criteria.where("xlj_name").is(dkCameraInfo.transferXljName(xlj.getXljName()))));
            if (xljDb == null) {
                return;
            }
            xljDb.setXljNature(xlj.getXljNature());
            xljDao.saveOrUpdate(xljDb);
        });
    }
}
